"""
@name : tags
@author : FanMY_71
@projectname: Selling-Idea
@Time: 2022/9/5-20:45
"""
from flask import Blueprint, request
from flask_restful import Api, Resource

from libs.handler import default_error_handler
from libs.response import generate_response
from model import db
from model.tag import Tag

tag_bp = Blueprint("tag", __name__, url_prefix="/v1")
api = Api(tag_bp)


class TagView(Resource):
    def put(self):
        """
        点赞
        获取文章id、用户id
        :return:点赞成功、文章id
        """
        user_id = request.json.get("userid")
        article_id = request.json.get("articleid")
        # 查找用户的点赞信息
        tag_infos = Tag.query.filter_by(user_id=user_id).all()
        for tag_info in tag_infos:
            # 如果该用户曾经点赞过该文章
            if tag_info.article_id == article_id and tag_info.tag == "Y":
                # 取消点赞
                tag_info.tag = "N"
                db.session.add(tag_info)
                db.session.commit()
                return generate_response(message="已取消点赞", data=article_id)
        # 用户没有点赞过该文章
        new_tag = Tag(user_id=user_id, article_id=article_id, tag="Y")
        db.session.add(new_tag)
        db.session.commit()
        return generate_response(message="点赞成功", data=article_id)


api.add_resource(TagView, "/tags")
api.handle_error = default_error_handler
